import { useEffect, useState, forwardRef, useImperativeHandle, } from "react";
import "./StoPaginator.scss";

interface IProps {
  ref: any;
  totalPages: number;
  currentPage: number;
  onPageChange: (n: number) => void;
}

/* 石头表格对外暴露的API类型定义 */
export interface StoPaginatorApi {
  // 对外暴露翻页方法
  turnToPage: (n: number) => void;
}


// 页码起止对/[起始页,结束页] 用于绘制一片连续的页码
// 起止页码都不给时 绘制一个省略号
type startEndPair = [number?, number?];

const StoPaginator = forwardRef<StoPaginatorApi, IProps>(

  /* ============================================================= */

  (
    {
      totalPages,
      currentPage: _currentPage,
      onPageChange,
    },
    ref
  ) => {
    /* 
      完整渲染：[1,10]
      首乌+省略+威武：[[1,5],[],[96,100]]
      首尔+省略+服务+省略+威尔：[[1,2],[],[11,15],[],[99,100]]
      */
    const _render = (arr: startEndPair[]) => {
      return arr.map(([startPage, endPage]) => {
        // [a,b]
        if (startPage && endPage) {
          // 构造页码数组 [16,17,18,19,20]
          const pagerArr = [];
          for (let i = startPage; i <= endPage; i++) {
            pagerArr.push(i);
          }

          return pagerArr.map((p) => (
            <li onClick={() => {
              turnToPage(Number(p))
            }} className={p === currentPage ? "current" : ""} key={p}>
              {p}
            </li>
          ));
        }

        // []
        return (
          <span key="space" className="space">
            ...
          </span>
        );
      });
    };

    /* 根据currentPage和totalPage 绘制页码 */
    const renderPagers = () => {
      /* 大猩猩渲染 */
      // return _render([[1, 3], [], [1, 10], [], [55, 58]]);

      /* 完整渲染：[1,10] */
      if (totalPages <= 10) {
        return _render([[1, totalPages]]);
      }

      /* 如果当前页位于边陲：[ [1,5]  []  [96,100] ] */
      if (currentPage <= 5 || currentPage >= totalPages - 4) {
        return _render([[1, 5], [], [totalPages - 4, totalPages]]);
      }

      /* 如果当前页位于腹地：[ [1,2],[],[48,52],[],[99,100] ] */
      return _render([
        [1, 2],
        [],
        [currentPage - 2, currentPage + 2],
        [],
        [totalPages - 1, totalPages],
      ]);
    };

    // 控制当前页
    const [currentPage, setCurrentPage] = useState(_currentPage);

    // 记录用户输入的当前页
    const [inputPage, setInputPage] = useState(_currentPage);

    /* 去到第几页 */
    const turnToPage = (n: number) => {
      /* 校正页码 */
      if (n > totalPages) n = 1;
      if (n < 1) n = totalPages;

      setCurrentPage(n);

      // 通知用户/父组件该翻页了
      onPageChange(n);
    };

    // 使用useImperativeHandle将API方法绑定到ref
    useImperativeHandle(ref, () => ({
      turnToPage,
    }));

    /* 当currentPage变化时 驱动userPage变化 */
    useEffect(
      () => {
        setInputPage(currentPage)
      },
      [currentPage]
    )

    return (
      <div className="sto-paginator-root">
        <div className="toilet-holder"></div>

        <div className="sto-paginator">
          <button onClick={() => turnToPage(1)}>首页</button>
          <button onClick={() => turnToPage(currentPage - 1)}>上页</button>

          {/* 一堆野马 */}
          <ul>{renderPagers()}</ul>

          <button onClick={() => turnToPage(currentPage + 1)}>下页</button>
          <button onClick={() => turnToPage(totalPages)}>末页</button>

          <input
            type="number"
            defaultValue={_currentPage}
            value={inputPage}
            onChange={(e) => {
              setInputPage(Number(e.target.value))
            }}
          />

          {/* 跳页按钮 */}
          <button onClick={() => turnToPage(inputPage)}>GO</button>
        </div>
      </div>
    );
  }

  /* ============================================================= */
);

export default StoPaginator;
